import {
    NotificationConstructorOptions,
    contextBridge,
    ipcRenderer,
} from "electron";
import { TimerMode } from "../renderer/src/types/GlobalEnum";
import { Notification } from "@electron/remote";
import { CacheSetting } from "../renderer/src/types/types";
import { electronAPI } from "@electron-toolkit/preload";

window.addEventListener("DOMContentLoaded", () => {
    const el = document.getElementById("time-main");
    if (el) {
        el.addEventListener("mouseenter", () => {
            ipcRenderer.send("set-ignore-mouse-events", false, {
                forward: false,
            });
        });
        el.addEventListener("mouseleave", () => {
            ipcRenderer.send("set-ignore-mouse-events", true);
        });
    }
});

// Custom APIs for renderer
const api = {
    quit: () => {
        ipcRenderer.send("quit");
    },
    setWindowSize: (opt: any) => {
        ipcRenderer.send("setWindowSize", opt);
    },
    sendCacheSettings: (data: CacheSetting) => {
        ipcRenderer.send("sendCacheSettings", data);
    },
    tip: (option: NotificationConstructorOptions) => {
        const tip = new Notification(option);
        tip.show();
    },
    changeMode: (callback) => {
        ipcRenderer.on("changeMode", (_, mode: TimerMode) => {
            callback(mode);
        });
    },
    changeDefaultTime: (callback) => {
        ipcRenderer.on("changeDefaultTime", (_, time: number) => {
            callback(time);
        });
    },
    changeDateSystem: (callback) => {
        ipcRenderer.on("changeDateSystem", () => {
            callback();
        });
    },
    changeShowSeconds: (callback) => {
        ipcRenderer.on("changeShowSeconds", () => {
            callback();
        });
    },
    getCacheSetting: (callback) => {
        ipcRenderer.on("getCacheSettings", () => {
            const data = callback();
            ipcRenderer.send("sendCacheSettings", data);
        });
    },
    piniaStoreSet: (callback) => {
        ipcRenderer.on(
            "pinia-store-set",
            (_, targetStoreName: string, jsonStr: string) => {
                callback(targetStoreName, jsonStr);
            }
        );
    },
    piniaStoreChange: (storeName, state) => {
        ipcRenderer.invoke("pinia-store-change", storeName, state);
    },
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
    try {
        contextBridge.exposeInMainWorld("electron", electronAPI);
        contextBridge.exposeInMainWorld("api", api);
    } catch (error) {
        console.error(error);
    }
} else {
    // @ts-ignore (define in dts)
    window.electron = electronAPI;
    // @ts-ignore (define in dts)
    window.api = api;
}
